<?php

class Listfriend extends Controller {

    public $error;
    public $friends;
    //public $userViewId;
    public $userLog;
    public $userViewId;
    public $userView;
    public $friendRelation;

    public function __construct() {
        parent::__construct();

        $this->_initialize();
    }

    public function __destruct() {
        parent::__destruct();
    }

    public function index() {
        if (isset($this->_session['user'])) {
            $this->userLog = $this->_session['user']['info'];
        } else {
            header('Location:index.php?c=login');
        }

        $this->_initialize();
        $this->template('friend');
    }

    public function _initialize() {
        if (isset($this->_session['user'])) {
            $this->userLog = $this->_session['user']['info'];
        } else {
            header('Location:index.php?c=login');
        }

        //Load model..
        $this->model('friend');
        $this->model('user');

        $this->userViewId = $this->userLog->id;
        $this->userView = NULL;
        if (!empty($this->_get['user'])) {
            $this->userView = $this->_get['user'];
            //Process in case user view one user that not existed with the username.
            $userInfo = $this->user->getInfoByUsername($this->userView);
            if (!empty($userInfo)) {
                $this->userViewId = $userInfo->id;
            }
        }
        $this->friends = $this->friend->gets($this->userLog->id,$this->userViewId);
        //Get friend relation..
        $this->friendRelation = $this->friend->getFriendRelation($this->userLog->id, $this->userViewId);
    }

    public function unfriend() {
        if (isset($this->_post['friend'])) {
            //Check csrf security...
            $token = $this->_post['friend']['token'];
            if ($token == $this->_token) {
                unset($this->_post['friend']['token']);
                $this->model('friend');
                $result = $this->friend->unfriend($this->userLog->id, $this->_post['friend']['idFriend']);
                if ((bool) $result) {
                    echo "{result:1, id:'{$this->_post['friend']['idFriend']}'}";
                } else {
                    echo "{result:0, id:'{$this->_post['friend']['idFriend']}'}";
                }
            }
        }
    }

}

?>
